/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int minDepth(TreeNode* root) {
        int res = INT_MAX;
        auto dfs = [&](this auto&& dfs, TreeNode* node, int cnt) -> void {
            if (node == nullptr)
                return;
            ++cnt;
            if (node->left == nullptr && node->right == nullptr)
            {   // node 是叶子
                res = min(res, cnt);
                return;
            }
            dfs(node->left, cnt);
            dfs(node->right, cnt);
        };
        dfs(root, 0);
        return root ? res : 0;
    }
};